import React, { useEffect, useState } from 'react';
import { withRouter } from 'react-router-dom';
import {
  Input,
  Form,
  Button,
  Select,
  Switch,
  message,
  Spin,
  Upload,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import marked from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/monokai-sublime.css';
import style from './redactContent.module.css';
import Api, { Url } from '../util/apiUrl';
import { dateFormat } from '../util/data';
import './redactContent.css';
// import { Router } from 'react-router-dom';
const { TextArea } = Input;
const { Option } = Select;
const layout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 24 },
};
const tailLayout = {
  wrapperCol: { offset: 3, span: 24 },
};

const RedactContent = (props) => {
  console.log('RedactContent props', props);

  const [markHTML, setMarkHTML] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [articleData, setArticleData] = useState({});
  const [skillType, setSkillType] = useState([]);
  const [fileList, setFileList] = useState([]);
  const [fileList2, setFileList2] = useState([
    // {
    //   uid: '-1',
    //   name: 'xxx.png',
    //   status: 'done',
    //   url: 'http://www.baidu.com/xxx.png',
    // },
  ]);

  const [form] = Form.useForm();
  useEffect(() => {
    if (props.articleData && Object.keys(props.articleData).length) {
      console.log('props.articleData', props.articleData);
      form.setFieldsValue({
        ...props.articleData,
        isRecommend: props.articleData.isRecommend == 1,
      });
      setMarkHTML(props.articleData.content);
      // 背景图
      if (props.articleData.img) {
        setFileList([
          {
            uid: '1',
            name: '背景图',
            status: 'done',
            url: props.articleData.img,
            reallyUrl:props.articleData.img
          },
        ]);
      }
      // 内容图
      if (props.articleData.contentImg) {
        setFileList2(
          props.articleData.contentImg.split(',').map((i, idx) => ({
            uid: idx + '',
            name: i.split('/').pop(),
            status: 'done',
            url: i,
            reallyUrl:i
          }))
        );
      }
    }
  }, [props.articleData]);
  useEffect(() => {
    getSkillType();
  }, []);

  marked.setOptions({
    renderer: new marked.Renderer(),
    gfm: true,
    pedantic: false,
    sanitize: false,
    tables: true,
    breaks: false,
    smartLists: true,
    smartypants: false,
    highlight: function (code) {
      return hljs.highlightAuto(code).value;
    },
  });
  let html = marked(markHTML || '');
  let upMarkHTML = markHTML.replace(/\/public\/admin\/temporary\//g, '/public/admin/articleContentImg/')

  // 增加/修改
  const onFinish = (values) => {
    values.isRecommend =
      values.isRecommend == 1 || values.isRecommend === true ? '1' : '0';
    values.contentImg = fileList2.map((i) => i.reallyUrl).join(',');
    values.author = window.localStorage.getItem('account');
    values.img = fileList[0] && fileList[0].reallyUrl;
    values.content = upMarkHTML
    if (props.articleData) {
      values.alterTime = dateFormat('YYYY-mm-dd HH:MM', new Date());
      console.log('修改', { ...props.articleData, ...values });
      setIsLoading(true);
      Api.alertArticle({ ...props.articleData, ...values })
        .then((res) => {
          console.log('修改成功', res);
          setIsLoading(false);
          message.success('修改文章成功');
          props.history.push('/admin/articleList');
        })
        .catch((err) => {
          console.log('添加失败', err);
          setIsLoading(false);
          message.error('添加文章失败');
        });
    } else {
      values.updateTime = dateFormat('YYYY-mm-dd HH:MM', new Date());
      console.log('Success:', values);
      setIsLoading(true);
      Api.addArticle(values)
        .then((res) => {
          console.log('添加成功', res);
          setIsLoading(false);
          message.success('添加文章成功');
          props.history.push('/admin/articleList');
        })
        .catch((err) => {
          console.log('添加失败', err);
          setIsLoading(false);
          message.error('添加文章失败');
        });
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 获取技术类别
  const getSkillType = () => {
    Api.getSkillType().then((res) => {
      console.log('获取到技术类别', res);
      setSkillType(res.data);
    });
  };

  // 上传背景的配置
  const uploadHandleChange = async (info) => {
    console.log('info', info);
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map((file, idx) => {
      if (file.response) {
        file.url = Url.replace('/admin/', '') + file.response[0].url;
        file.reallyUrl =
          Url.replace('/admin/', '') +
          '/public/admin/articleBgi/' +
          file.response[0].wsName;
      }
      return file;
    });
    setFileList(fileList);
    console.log('fileList', fileList);
  };
  // const uploadOnRemove=()=>{
  //   setFileList([])
  // }
  const props1 = {
    action: Url + 'upImgToTemporary',
    onChange: uploadHandleChange,
    // onRemove:uploadOnRemove,
    multiple: true,
  };

  // 上传内容的配置
  const uploadHandleChange2 = async (info) => {
    console.log('info2', info);
    let fileList = [...info.fileList];
    fileList = fileList.slice(-100);
    fileList = fileList.map((file, idx) => {
      if (file.response) {
        file.url = Url.replace('/admin/', '') + file.response[0].url;
        file.reallyUrl =
          Url.replace('/admin/', '') +
          '/public/admin/articleContentImg/' +
          file.response[0].wsName;
        file.name = file.response[0].wsName;
      }
      return file;
    });
    setFileList2(fileList);
    console.log('fileList', fileList);
  };
  // const uploadOnRemove=()=>{
  //   setFileList([])
  // }
  const props2 = {
    action: Url + 'upImgToTemporary',
    onChange: uploadHandleChange2,
    // onRemove:uploadOnRemove,
    multiple: true,
  };

  return (
    <>
      {isLoading ? (
        <div className={style.container}>
          <Spin size="large" className={style.spin} />
        </div>
      ) : null}
      <Form
        {...layout}
        form={form}
        name="basic"
        initialValues={articleData}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          label="标题"
          name="title"
          rules={[{ required: true, message: '请填写文章标题' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="技术类型"
          name="skillTypeId"
          rules={[{ required: true, message: '请选择技术类型' }]}
        >
          <Select
            style={{ width: 400 }}
            onChange={(e) => {
              console.log('类型', e);
            }}
          >
            {skillType.map((i) => (
              <Option value={i.id} key={i.id}>
                {i.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="是否推荐" name="isRecommend" valuePropName="checked">
          <Switch />
        </Form.Item>
        <Form.Item
          label="文章简介"
          name="synopsis"
          rules={[{ required: true, message: '请输入文章简介' }]}
        >
          <TextArea rows={4} />
        </Form.Item>
        <Form.Item
          label="文章标签"
          name="tags"
          rules={[{ required: true, message: '请选择文标签' }]}
        >
          <Input placeholder="多个标签以 , 分隔" />
        </Form.Item>
        <Form.Item label="文章背景图" name="img">
          <Upload {...props1} fileList={fileList}>
            <Button>
              <UploadOutlined /> 添加图片
            </Button>
          </Upload>
        </Form.Item>
        <Form.Item label="文章内容图" name="contentImg">
          <Upload {...props2} fileList={fileList2}>
            <Button>
              <UploadOutlined /> 添加内容图片
            </Button>
          </Upload>
        </Form.Item>
        <Form.Item
          label="内容"
          name="content"
          rules={[{ required: true, message: '填写内容' }]}
        >
          <div className={style.markdown}>
            <TextArea
              value={markHTML}
              className={style.markdownContent}
              rows={25}
              onChange={(e) => {
                setMarkHTML(e.target.value);
              }}
              onPressEnter={(e) => {
                setMarkHTML(e.target.value);
              }}
              placeholder="文章内容"
            />
            <div
              className={style.preview + ' preview'}
              dangerouslySetInnerHTML={{ __html: html || '内容预览' }}
              // '文章预览: <hr style="border:0.5px solid #d9d9d9"/>'
            ></div>
          </div>
        </Form.Item>

        <Form.Item {...tailLayout}>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};

export default withRouter(RedactContent);
